#include "EpilThenBlockParser.h"
#include "EpilParserException.h"
#include "EpilExpressionParser.h"
#include "EpilChunkParser.h"
#include "EpilPointerHelper.h"


EpilThenBlockParser::EpilThenBlockParser( EpilTokenStream & tokens )
: EpilSyntaxParserBase( tokens )
{
}


void EpilThenBlockParser::Parse()
{
	// then_block -> [IF | ELSEIF] expr THEN block
	m_thenBlock = new EpilThenBlockCode( this->GetTokens().GetCurrentToken().location );
	this->GetTokens().MoveToNext();

	EpilExpressionParser exprParser( this->GetTokens() );
	try
	{
		exprParser.Parse();
	}
	catch( ... )
	{
		EpilPointerHelper::SafeDelete( m_thenBlock );
		throw;
	}
	m_thenBlock->SetCondition( exprParser.GetExpression() );

	if( this->GetTokens().GetCurrentToken().type != ETT_KwThen )
	{
		EpilPointerHelper::SafeDelete( m_thenBlock );
		throw EpilParserException( t("\'then\' expected."), this->GetTokens().GetCurrentToken().location );
	}
	this->GetTokens().MoveToNext();

	EpilChunkParser chunkParser( this->GetTokens() );
	try
	{
		chunkParser.Parse();
	}
	catch( ... )
	{
		EpilPointerHelper::SafeDelete( m_thenBlock );
		throw;
	}
	m_thenBlock->SetChunk( chunkParser.GetChunk() );
}